package com.dd.ms.auth.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dd.ms.auth.mapper.RefreshTokenMapper;
import com.dd.ms.auth.pojo.DO.RefreshTokenDO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/8/6 11:58
 * @Description 类功能作用说明
 */
@Repository
@RequiredArgsConstructor
public class RefreshTokenRepository {

    private final RefreshTokenMapper refreshTokenMapper;

    /**
     * 清除过期token并插入新的token
     *
     * @param refreshTokenDO
     */
    public void save(RefreshTokenDO refreshTokenDO) {
        LambdaQueryWrapper<RefreshTokenDO> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RefreshTokenDO::getUserId, refreshTokenDO.getUserId());
        lqw.eq(RefreshTokenDO::getDeviceFingerprint, refreshTokenDO.getDeviceFingerprint());
        RefreshTokenDO existOne = refreshTokenMapper.selectOne(lqw);
        if (existOne != null) {
            refreshTokenMapper.updateById(refreshTokenDO);
        } else {
            refreshTokenMapper.insert(refreshTokenDO);
        }
    }

    public void removeRefreshTokenByUserId(Long userId) {
        LambdaQueryWrapper<RefreshTokenDO> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RefreshTokenDO::getUserId, userId);
        refreshTokenMapper.delete(lqw);
    }
}
